// base_web_view.dart
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:webview_flutter/webview_flutter.dart';

class BaseWebView extends StatefulWidget {
  static final String sName = '/base_web_view';

  const BaseWebView({
    Key? key,
    required this.title,
    required this.url,
  }) : super(key: key);

  final String title;
  final String url;

  @override
  State<BaseWebView> createState() => _BaseWebViewState();
}

class _BaseWebViewState extends State<BaseWebView> {
  late final WebViewController _controller;
  int _progressValue = 0;
  String _dynamicTitle = ''; // 新增：动态标题状态变量

  @override
  void initState() {
    super.initState();
    _dynamicTitle = widget.title; // 初始标题使用传入的 title
    _init();
  }

  Future<void> _init() async {
    // 创建公共控制器配置
    _controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
    // 新增：JavaScript 通信通道用于获取标题
      ..addJavaScriptChannel('TitleChannel', onMessageReceived: (message) {
        if (!mounted) return;
        setState(() {
          // 如果网页无标题，保留原始标题
          _dynamicTitle = message.message.isEmpty
              ? widget.title
              : message.message;
        });
      })
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int progress) {
            if (!mounted) return;
            setState(() => _progressValue = progress);
          },
          // 新增：页面加载完成后获取标题
          onPageFinished: (String url) async {
            // 无论本地还是远程都通过 JS 获取标题
            await _controller.runJavaScript('''
              TitleChannel.postMessage(document.title);
            ''');
          },
        ),
      );

    // 根据 URL 类型选择加载方式
    if (widget.url.startsWith('http')) {
      await _controller.loadRequest(Uri.parse(widget.url));
    } else {
      // 加载本地 HTML 并设置资源基准路径
      final htmlContent = await rootBundle.loadString(widget.url);
      await _controller.loadHtmlString(
        htmlContent,
        baseUrl: 'https://localhost/', // 确保本地资源正确加载
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: false,
      onPopInvoked: (didPop) async => _handleBackPress(context),
      child: Scaffold(
        appBar: AppBar( // 修改：使用动态标题
          title: Text(_dynamicTitle),
          centerTitle: true,
        ),
        body: Stack(
          children: [
            WebViewWidget(controller: _controller),
            if (_progressValue != 100)
              LinearProgressIndicator(
                value: _progressValue / 100,
                backgroundColor: Colors.transparent,
                minHeight: 2,
              )
          ],
        ),
      ),
    );
  }

  Future<void> _handleBackPress(BuildContext context) async {
    // 优先处理网页返回
    final bool canGoBack = await _controller.canGoBack();
    if (canGoBack) {
      await _controller.goBack();
      return;
    }

    // 安全关闭当前页面
    if (mounted ) {
      Navigator.pop(context);
    }
  }
}